package top.wshape1.shiziapi.message.websocket;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import top.wshape1.shiziapi.common.constant.RedisConstant;
import top.wshape1.shiziapi.message.constant.WebSocketConstant;
import top.wshape1.shiziapi.message.context.MachineNodeContextHandler;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-01-24
 */

@Component
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Resource
    private WsSessionManager sessionManager;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private MachineNodeContextHandler machineNodeContextHandler;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        try {
            String id = session.getAttributes().get(WebSocketConstant.USER_ID).toString();
            sessionManager.add(id, session);
            // 建立成功，存储对应的节点ID到Redis
            redisTemplate.opsForValue().set(RedisConstant.WEBSOCKET_USER_NODE_KEY + id, machineNodeContextHandler.MACHINE_ID);
        } catch (Exception e) {
            log.error("尝试添加session失败", e);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        try {
            String id = session.getAttributes().get(WebSocketConstant.USER_ID).toString();
            sessionManager.remove(id);
            redisTemplate.delete(RedisConstant.WEBSOCKET_USER_NODE_KEY + id);
        } catch (Exception e) {
            log.error("尝试移除session失败", e);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
            String payload = message.getPayload();
            log.info("接收到{}发来的消息: {}", session.getAttributes().get(WebSocketConstant.USER_ID), payload);
            if ("ping".equals(payload)) {
                session.sendMessage(new TextMessage("pong"));
            }
        } catch (Exception e) {
            log.error("尝试接收消息失败", e);
        }
    }
}
